import versionControlVue from './index.vue';

import axios from 'axios';

const versionControl = function(Vue, options = {}) {

    const versionControlConstructor = Vue.extend(versionControlVue);

    const request = axios.create({
        baseURL : options.ip
    })

    let versionControlInstance = null

    /**
     * ip : 服务器ip
     * version : 版本号
     * appId : 应用id
     * 
    */

    const app = {
        data : {},
        extend(){
            versionControlInstance = new versionControlConstructor({
                data : this.data,
                methods : {
                    download : this.download,
                    ignore : this.ignore,
                    close : this.close
                }
            }).$mount();

            document.body.appendChild(versionControlInstance.$el);
        },
        close(){
            if(versionControlInstance){
                document.body.removeChild(versionControlInstance.$el);
            }
        },
        download(version, name){
            const a = document.createElement('a')
            a.download = name || true
            a.href = version.url
            a.click()
        },
        ignore(version){
            localStorage.setItem('ignoreVersion', version.vcVersion)
        },
        getIgnore(){
            let ignore = localStorage.getItem('ignoreVersion') || 0
            return String(parseInt(ignore)) == 'NaN' ? 0 : parseInt(ignore)
        }
    }

    return function (){
        return request({
            method : 'post',
            url : '/api/version/check',
            data : {
                version : options.version,
                appId : options.appId,
                ignoreVersion : app.getIgnore()
            }
        }).then(res => {
            if (!options.custom) {
                app.data = res.data.data
                if(app.data && app.data.isNew){
                    app.extend()
                }
                return Promise.resolve(app)
            }else{
                return Promise.resolve(res.data.data)
            }
        })
    }
};

export default versionControl;
